<script setup>
import { reactive, ref } from 'vue'
import { Search } from '@element-plus/icons-vue'
import AddAchievement from './components/AddAchievement.vue'
import * as XLSX from 'xlsx'
import { dayjs } from 'element-plus'
import { handleLogger } from '@renderer/util/common'

const levelOpts = ref([])
async function handleGetLevelOpts() {
  const res = await window.api.getAllDealerLevel()
  console.log(res)
  levelOpts.value = res
}
handleGetLevelOpts()

function disabledDate(date) {
  return dayjs(date).isAfter(dayjs())
}

const filterState = reactive({
  time: [dayjs().format('YYYY-MM-01'), dayjs().format('YYYY-MM-DD')],
  name: '',
  level: ''
})

const tableCols = [
  {
    key: 'performance_date',
    label: '日期'
  },
  {
    key: 'parent_dealer_name',
    label: '绑定关系'
  },
  {
    key: 'dealer_name',
    label: '经销商名称'
  },
  {
    key: 'dealer_level_name',
    label: '经销商等级'
  },
  {
    key: 'performance_money',
    label: '个人业绩',
    sort: true
  },
  {
    key: 'modify_time',
    label: '最近更新时间'
  }
]
const listState = reactive({
  page: 1,
  pageSize: 20,
  list: [],
  total: 0,
  loading: false
})
async function getList() {
  listState.loading = true
  const res = await window.api.getPerformanceList(
    listState.pageSize,
    listState.page - 1,
    filterState.time ? filterState.time[0] : '',
    filterState.time ? filterState.time[1] : '',
    filterState.name,
    filterState.level
  )
  setTimeout(() => {
    listState.loading = false
  }, 500)

  listState.total = res.total
  listState.list = res.rows
}
getList()
function changePageNo(page) {
  listState.page = page
  getList()
}

function handleRefreshList() {
  listState.page = 1
  getList()
}

const showAddAchievement = ref(false)

async function handleExportList() {
  handleLogger('导出业绩详情列表数据')
  const res = await window.api.getPerformanceExport(
    filterState.time ? filterState.time[0] : '',
    filterState.time ? filterState.time[1] : '',
    filterState.name,
    filterState.level
  )
  let listData = res.rows || []
  console.log(listData)

  // 设置 Excel 表头
  const headers = ['日期', '经销商名称', '经销商等级', '个人业绩', '最近更新时间']

  // 将 listData 转换为合适的格式，每项数据对应 '姓名'、'年龄'、'性别'
  const processedData = listData.map((item) => ({
    日期: item.performance_date,
    经销商名称: item.dealer_name,
    经销商等级: item.dealer_level_name,
    个人业绩: item.performance_money,
    最近更新时间: item.modify_time
  }))

  // 使用 XLSX.utils.json_to_sheet 生成 sheet，添加表头
  const ws = XLSX.utils.json_to_sheet(processedData, { header: headers })

  // 创建新的工作簿
  const wb = XLSX.utils.book_new()
  // 将 sheet 添加到工作簿
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1')

  // 导出 Excel 文件
  XLSX.writeFile(wb, `业绩详情${dayjs().format('YYYYMMDD')}.xlsx`)
}
</script>

<template>
  <div class="achievement-detail-page">
    <div class="top-filter-wrap">
      <div style="width: 350px">
        <el-date-picker
          v-model="filterState.time"
          type="daterange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          format="YYYY-MM-DD"
          value-format="YYYY-MM-DD"
          :disabled-date="disabledDate"
        />
      </div>
      <el-input
        v-model="filterState.name"
        placeholder="请输入经销商名称"
        style="width: 200px"
        :prefix-icon="Search"
      ></el-input>
      <el-select
        v-model="filterState.level"
        clearable
        placeholder="请选择经销商等级"
        style="width: 200px"
      >
        <el-option
          v-for="item in levelOpts"
          :key="item.dealer_level_id"
          :label="item.dealer_level_name"
          :value="item.dealer_level_id"
        ></el-option>
      </el-select>
      <el-button type="primary" @click="handleRefreshList">查询</el-button>
      <el-button type="primary" @click="handleExportList">导出</el-button>
      <el-button type="primary" @click="showAddAchievement = true">录入</el-button>
    </div>
    <div v-loading="listState.loading" class="table-wrap">
      <el-table :data="listState.list" style="width: 100%" border @sort-change="handleTableSort">
        <el-table-column
          v-for="item in tableCols"
          :key="item.key"
          :prop="item.key"
          :label="item.label"
          align="center"
          :width="item.width"
          :sortable="item.sort ? 'custom' : false"
        >
        </el-table-column>
        <template #empty>
          <div class="table-no-data">
            <img src="@renderer/assets/img/empty-data.png" />
            <span>暂无数据</span>
          </div>
        </template>
      </el-table>
      <mPage
        :page-size="listState.pageSize"
        :page_no="listState.page"
        style="display: flex; justify-content: flex-end; margin-top: 20px"
        :total="listState.total"
        @handle-current-change="changePageNo"
      />
    </div>
  </div>

  <!-- 录入业绩 -->
  <AddAchievement v-model:show="showAddAchievement" @success="handleRefreshList" />
</template>
